# -*- coding: utf-8 -*-
import scrapy
import datetime
import lianzhong_api
import json
import time
import requests
import redis
import base64

from scrapy.utils.project import get_project_settings
import pymysql
setting=get_project_settings()

class qunar(scrapy.Spider):

    name = 'ota_qunar_hotel'

    def __init__(self,*args,**kwargs):
        self.CRS_ID = kwargs['CRS_ID']
        self.username = kwargs['username']

        password=kwargs['password'][1:]
        self.password = base64.b64decode(password)
        self.batch_no = kwargs['batch_no']
        self.now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(self.username,self.password)

        HOST = setting.get('HOST')
        PORT = setting.get('PORT')
        USER = setting.get('USER')
        PASSWD = setting.get('PASSWD')
        DB = setting.get('DB')
        CHARSET = setting.get('CHARSET')
        self.conn = pymysql.connect(host=HOST, port=PORT, user=USER, passwd=PASSWD, db=DB, charset=CHARSET)
        self.cur = self.conn.cursor()
        #
        # RHOST = setting.get('RHOST')
        # RPORT = setting.get('RPORT')
        # RPASSWORD = setting.get('RPASSWORD')
        # RDB = setting.get('RDB')
        # self.r = redis.Redis(host=RHOST, port=RPORT, password=RPASSWORD, db=RDB,charset='utf-8',decode_responses=True)

        # self.batch_no = datetime.datetime.now().strftime('%Y%m%d')
        self.headers={
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'accept':'*/*',
            'content-type':'application/x-www-form-urlencoded',
            "referer": "https://ebooking.qunar.com/ebPage/login.html"
        }
        self.headers2 = {
            'x-requested-with': 'XMLHttpRequest',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'referer': 'https://ebooking.qunar.com/ebPage/roomControl/list.html',
            'content-type': 'application/json'
        }

        now_time = datetime.datetime.now()
        yesterday = now_time + datetime.timedelta(days=0)
        self.strdate1 = yesterday.strftime('%Y-%m-%d')
        yesterday = now_time + datetime.timedelta(days=6)
        self.strdate2 = yesterday.strftime('%Y-%m-%d')

    def start_requests(self):
        url = 'http://ebooking.qunar.com/ebPage/login.html'
        yield scrapy.Request(url, meta={'cookiejar': 1}, callback=self.post_login)

    def post_login(self, response):
        image_url = 'https://user.qunar.com/captcha/api/image?k={en7mni(z&p=ucenter_login&c=ef7d278eca6d25aa6aec7272d57f0a9a'
        yield scrapy.Request(
            url=image_url,
            dont_filter=True,
            meta={
                'cookiejar': response.meta['cookiejar']
            },
            callback=self.get_image
        )

    def get_image(self, response):
        images=response.body
        with open('image.png','wb') as f:
            f.write(images)

        captchaCode= lianzhong_api.main(
                        'baozhengxing',
                        '1qaz2wsx@123',
                        'image.png',
                        "http://v1-http-api.jsdama.com/api.php?mod=php&act=upload",
                        '4',
                        '4',
                        '1001',
                        ''
                    )
        try:
            captchaCode=json.loads(captchaCode)['data']['val']
            print(captchaCode)
            body = {
                "vcode": captchaCode,
                "username": self.username,
                "password": self.password,
                "remember": "1",
                "prenum": "86",
                "isHalfLogin": "false"
            }

            yield scrapy.FormRequest(
                url='https://user.qunar.com/webApi/logins.jsp',
                callback=self.after_login,
                dont_filter=True,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                headers=self.headers,
                formdata=body,
                method='POST'
            )
        except:
            image_url = 'https://user.qunar.com/captcha/api/image?k={en7mni(z&p=ucenter_login&c=ef7d278eca6d25aa6aec7272d57f0a9a'
            # print(image_url)
            yield scrapy.Request(
                url=image_url,
                dont_filter=True,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                callback=self.get_image
            )


    def after_login(self, response):
        print(response.body.decode('utf-8'))
        code=json.loads(response.body.decode('utf-8'))['errcode']

        if code==200:
            print("########################################正确############################################")
            # sql = "update hotel_users set Qunar_Status=0 where Qunar_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Qunar_Username,Qunar_Status,Qunar_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Qunar_Status='%s',Qunar_Date='%s',Qunar_Username='%s'" % (self.CRS_ID, self.username, 0, self.now, self.batch_no, 0, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()
        elif code==21022:

            print("########################################错误############################################")
            # sql = "update hotel_users set Qunar_Status=1 where Qunar_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Qunar_Username,Qunar_Status,Qunar_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Qunar_Status='%s',Qunar_Date='%s',Qunar_Username='%s'" % (self.CRS_ID, self.username, 1, self.now, self.batch_no, 1, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

        elif code == 21035:
            print("########################################为了您的账号安全，请使用手机验证码登录############################################")
            # sql = "update hotel_users set Qunar_Status=2 where Qunar_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Qunar_Username,Qunar_Status,Qunar_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Qunar_Status='%s',Qunar_Date='%s',Qunar_Username='%s'" % (self.CRS_ID, self.username, 2, self.now, self.batch_no, 2, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

        elif code == 12002:
            print("########################################仅支持手机/邮箱/用户名登录###########################################")
            # sql = "update hotel_users set Qunar_Status=3 where Qunar_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Qunar_Username,Qunar_Status,Qunar_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Qunar_Status='%s',Qunar_Date='%s',Qunar_Username='%s'" % (self.CRS_ID, self.username, 3, self.now, self.batch_no, 3, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

        else:
            image_url = 'https://user.qunar.com/captcha/api/image?k={en7mni(z&p=ucenter_login&c=ef7d278eca6d25aa6aec7272d57f0a9a'
            # print(image_url)
            yield scrapy.Request(
                url=image_url,
                dont_filter=True,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                callback=self.get_image
            )



